package com.superman.mvpframe.client.router;

import com.google.web.bindery.event.shared.HandlerRegistration;
import com.superman.mvpframe.client.gin.XGinjector;
import com.superman.mvpframe.client.history.IHtml5Historian;
import com.superman.mvpframe.client.history.PopStateEvent;
import com.superman.mvpframe.client.history.PopStateHandler;
import com.superman.mvpframe.client.utils.StringUtils;

/**
 * 页面路由返回工具类
 * 
 * @author superman
 * @version 2018年8月8日下午2:53:22
 */
public class MyPageRouterPopHelper {

	/**
	 * pop内部回调
	 * 
	 * @author superman
	 * @version 2018年8月8日下午2:53:24
	 */
	public interface PopAfterCallBack {
		/**
		 * pop成功
		 * 
		 * @author superman
		 * @version 2018年8月8日 下午2:54:24
		 */
		void onSuccess();
	}

	private IHtml5Historian historian = XGinjector.INSTANCE.getHtml5Historian();

	private HandlerRegistration hr = null;

	private boolean upToPop = false;

	/**
	 * 是否在页面回退pop进行中
	 * 
	 * @author superman
	 * @version 2018年8月8日 下午2:53:26
	 * @return upToPop
	 */
	public boolean isFireFromBackToPageEvent() {
		return upToPop;
	}

	/**
	 * pop一层
	 * 
	 * @author superman
	 * @version 2018年8月8日 下午2:53:55
	 * @param callBack
	 */
	public void pop(final PopAfterCallBack callBack) {
		if (historian.length() > 0) {
			hr = historian.addPopStateHandler(new PopStateHandler() {

				@Override
				public void onPopStateEvent(PopStateEvent event) {
					upToPop = false;
					if (callBack != null)
						callBack.onSuccess();
					hr.removeHandler();
				}
			});
			upToPop = true;
			historian.back();
		} else {
			if (callBack != null)
				callBack.onSuccess();
		}

	}

	/**
	 * pop到首页
	 * 
	 * @author superman
	 * @version 2018年8月8日 下午2:54:04
	 * @param callBack
	 */
	public void popHome(final PopAfterCallBack callBack) {
		popTo("", callBack);
	}

	/**
	 * pop到指定页面
	 * 
	 * @author superman
	 * @version 2018年8月8日 下午2:54:07
	 * @param token
	 * @param callBack
	 */
	public void popTo(final String token, final PopAfterCallBack callBack) {
		if (historian.length() > 0) {
			hr = historian.addPopStateHandler(new PopStateHandler() {

				@Override
				public void onPopStateEvent(PopStateEvent event) {
					if (StringUtils.isEmpty(event.getData())) {
						upToPop = false;
						if (callBack != null)
							callBack.onSuccess();
						hr.removeHandler();
					} else {
						if (StringUtils.isEmpty(token)) {
							historian.back();
						} else {
							String data = event.getData();
							String[] ts = token.split(":");
							String[] ds = data.split(":");

							if (ts[0].equals(ds[0])) {
								upToPop = false;
								if (callBack != null)
									callBack.onSuccess();
								hr.removeHandler();
							} else
								historian.back();
						}
					}
				}
			});
			upToPop = true;
			historian.back();
		} else {
			if (callBack != null)
				callBack.onSuccess();
		}

	}

}
